package com.healthteches.write;

import de.beckhoff.jni.JNIByteBuffer;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
import de.beckhoff.jni.tcads.AmsAddr;

import java.util.Scanner;

public class WriteArray {
  public static void main(String[] args) throws Exception {
    byte[] lowByte = new byte[40];
    long nPort, nErr;
    AmsAddr addr = new AmsAddr();

    // Open communication
    nPort = AdsCallDllFunction.adsPortOpen();
    nErr = AdsCallDllFunction.getLocalAddress(addr);
    addr.setPort(801);

    if (nErr != 0) {
      System.out.println("Error: Open Communication: 0x" + Long.toHexString(nErr));
    }
    byte low[] = new byte[10];
    // Read value by IndexGroup and IndexOffset

    if (nErr != 0) {
      System.out.println("Error: Read by handle: 0x" + Long.toHexString(nErr));
    } else {
      Scanner Scan = new Scanner(System.in);
      for (int i = 0; i < 10; i = i + 1) {

        low[i] = Scan.nextByte();
      }
      // PLC datatype int consists of two bytes. Get them.
      JNIByteBuffer dataBuff = new JNIByteBuffer(low.length);
      dataBuff.setByteArray(low);

      nErr =
          AdsCallDllFunction.adsSyncWriteReq(
              addr,
              0x4040, // Index Group
              0x0, // Index Offset
              low.length,
              dataBuff);
    }

    // Close communication
    nErr = AdsCallDllFunction.adsPortClose();
    if (nErr != 0) {
      System.out.println("Error: Close Communication: 0x" + Long.toHexString(nErr));
    }

    try {
      System.in.read();
    } catch (Exception e) {
      System.out.println("Error: Close program");
    }
  }
}
